import axios, { AxiosRequestConfig } from 'axios'

// 配置请求头和请求路径
axios.defaults.baseURL = 'http://localhost:3000'
axios.defaults.timeout = 1000 * 30
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8'

// 请求拦截
axios.interceptors.request.use(
    config => {
      return config
    },
    error => {
      return error
    }
)

//响应拦截
axios.interceptors.response.use(
    res => {
      if (res.data.code === 200) {
        return res.data.data
      } else {
        return Promise.reject(res.data.message)
      }
    },
    error => {
      return Promise.reject(error)
    }
)

// 定义统一响应格式
interface ResType<T> {
  code: number,
  data: T,
  message: string
}

// 定义抽象请求方法
interface Http {
  get<T>(url: string, params?: unknown, config?: AxiosRequestConfig): Promise<ResType<T>>

  post<T>(url: string, params?: unknown, config?: AxiosRequestConfig): Promise<ResType<T>>

  upload<T>(url: string, file: unknown): Promise<ResType<T>>

  download(url: string): void
}

const http: Http = {
  get: (url, params, config) => {
    return new Promise((resolve, reject) => {
      axios
          .get(url, { params, ...config })
          .then(res => {
            resolve(res.data)
          })
          .catch(err => {
            reject(err.data)
          })
    })
  },
  post: (url, params, config) => {
    return new Promise((resolve, reject) => {
      axios
          .post(url, { params, ...config })
        .then((res) => {
          if (true) {
              return
              console.log(123);
          } else {
            console.log(2);
            }
            resolve(res.data)
          })
          .catch((err) => {
            reject(err.data)
          })
    })
  },
  upload: (url, file) => {
    return new Promise((resolve, reject) => {
      axios
          .post(url, file, {
            headers: { 'Content-Type': 'multipart/form-data' },
          })
          .then((res) => {
            resolve(res.data)
          })
          .catch((err) => {
            reject(err.data)
          })
    })
  },
  download: (url: string) => {
    const a = document.createElement('a')
    a.href = url
    a.download = url.split('/').pop() || '未命名文件'
    a.click()
  }
}